package com.itheima.health.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @program: itcast_health
 * @create: 2019-10-23 16:26
 * @author: li he
 * @description:
 */
@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    @Transactional
    public void add(ArrayList<OrderSetting> orderSettingList) {


        for (OrderSetting orderSetting : orderSettingList) {
            //先去查询数据库
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

            OrderSetting orderSettingDb = orderSettingDao.findByDate(sdf.format(orderSetting.getOrderDate()));

            if (orderSettingDb == null){
                //如果没有查到数据则代表这一天没有设置过,就进行插入方法
                orderSettingDao.add(orderSetting);
            } else {
                //如果查到数据 则代表已经添加过数据 就进行更新方法
                //在更新之前先比较一下当前已预约人数 和 和设置预约人数
                if (orderSetting.getNumber() < orderSettingDb.getReservations()){
                    //代表 设置预约人数 小于 已经预约人数 属于异常
                    String date = sdf.format(orderSetting.getOrderDate());
                    throw new RuntimeException(date + ":设置的预约人数不能小于可预约人数 ! ! !");
                } else {
                    //正常更新场景
                    orderSettingDao.edit(orderSetting);
                }
            }
        }
    }

    @Override
    public List<OrderSetting> findByMonth(String month) {
        String startDate = month +"-01";
        String endDate = month + "-31";
        return orderSettingDao.findByMonth(startDate,endDate);
    }

    @Override
    @Transactional
    public void edit(OrderSetting orderSetting) {
        orderSettingDao.edit(orderSetting);
    }

    @Override
    public void clearOneMonthAgoOrderSetting() {

        Calendar calendar = Calendar.getInstance();
        //向前调整1个月
        calendar.add(Calendar.MONTH,-1);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time = calendar.getTime();
        String oneMonthAge = sdf.format(time);
        orderSettingDao.delOrderSettingByTime(oneMonthAge);

    }
}